<template>
  <div class="online-custom-list" style="padding: 2px 4px">
    <van-button v-if="operationVisible(SysCustomWidgetOperationType.ADD)"
      class="add-btn" color="#00AE1C" plain icon="plus" size="small"
      @click="onOperationClick(getOperation(SysCustomWidgetOperationType.ADD))"
    >
      {{ (getOperation(SysCustomWidgetOperationType.ADD) || {}).name || '添加' }}
    </van-button>
    <template v-if="cardWidget">
      <CustomList class="list-box" ref="list" :loadData="onLoadData">
        <component class="list-item" slot-scope="scope"
          :is="getComponent"
          :rowData="scope.data"
          :widget="cardWidget"
          :parentWidget="widget"
        >
          <van-row slot="menu" v-if="operationVisible(SysCustomWidgetOperationType.DELETE, scope.data) || operationVisible(SysCustomWidgetOperationType.EDIT, scope.data)"
            type="flex" justify="end"
            style="border-top: 1px solid #D9DBDD; padding-top: 10px;"
          >
            <!-- <van-icon v-if="operationVisible(SysCustomWidgetOperationType.DELETE, scope.data)"
              name="delete-o" color="#EE0A24" size="14px"
              @click="onOperationClick(getOperation(SysCustomWidgetOperationType.DELETE), scope.data)"
            >
              <span style="margin-left: 4px;">{{(getOperation(SysCustomWidgetOperationType.DELETE) || {}).name || '删除'}}</span>
            </van-icon> -->
            <!-- <van-icon v-if="operationVisible(SysCustomWidgetOperationType.EDIT, scope.data)"
              name="records" color="#FF7700" size="14px" style="margin-left: 8px;"
              @click="onOperationClick(getOperation(SysCustomWidgetOperationType.EDIT), scope.data)"
            >
              <span style="margin-left: 4px;">{{(getOperation(SysCustomWidgetOperationType.EDIT) || {}).name || '编辑'}}</span>
            </van-icon> -->
            <i class="mobile-font icon-delete" style="color:#EE0A24; font-size:14px;"
            v-if="operationVisible(SysCustomWidgetOperationType.DELETE, scope.data)"
            @click="onOperationClick(getOperation(SysCustomWidgetOperationType.DELETE), scope.data)">
              <span style="margin-left: 4px;">{{(getOperation(SysCustomWidgetOperationType.DELETE) || {}).name || '删除'}}</span>
            </i>
            <i class="mobile-font icon-edit" style="color:#FF7700; font-size:14px;margin-left: 8px;"
            v-if="operationVisible(SysCustomWidgetOperationType.EDIT, scope.data)"
            @click="onOperationClick(getOperation(SysCustomWidgetOperationType.EDIT), scope.data)">
              <span style="margin-left: 4px;">{{(getOperation(SysCustomWidgetOperationType.EDIT) || {}).name || '编辑'}}</span>
            </i>
          </van-row>
        </component>
      </CustomList>
    </template>
  </div>
</template>

<script>
import { findItemFromList } from '@/utils';
import CustomList from '@/components/CustomList.vue';

export default {
  name: 'onlineCustomList',
  props: {
    value: {
      type: Array,
      default: () => []
    },
    widget: {
      type: Object
    }
  },
  components: {
    CustomList
  },
  inject: ['form'],
  provide () {
    return {
      parentWidget: this.widget
    }
  },
  data () {
    return {}
  },
  methods: {
    async onTableDataListChange (dataList) {
      if (
        !this.form().isEdit &&
        typeof this.widget.eventInfo[this.OnlineFormEventType.AFTER_LOAD_TABLE_DATA] === 'function'
      ) {
        dataList = await this.widget.eventInfo[this.OnlineFormEventType.AFTER_LOAD_TABLE_DATA](dataList);
      }
      return dataList;
    },
    onLoadData (pageNum) {
      return new Promise((resolve, reject) => {
        resolve({
          dataList: this.value,
          totalCount: (this.value || []).length,
          finished: true
        });
      });
    },
    hasOperator (type) {
      let temp = this.getOperation(type);
      return temp && temp.enabled;
    },
    getOperation (type) {
      return findItemFromList(this.widget.operationList, type, 'type');
    },
    operationVisible (type, data) {
      let operation = this.getOperation(type);
      if (operation == null) return false;
      return !this.form().readOnly && this.hasOperator(type) && this.form().checkOperationVisible(operation, data);
    },
    onOperationClick (operation, row) {
      if (operation.type === this.SysCustomWidgetOperationType.BATCH_DELETE) {
        this.onDeleteRow(row);
      } else if (operation.type === this.SysCustomWidgetOperationType.DELETE) {
        this.onDeleteRow(row);
      } else {
        this.form().handlerOperation(
          operation,
          row,
          this.widget,
          (res) => {
            this.handlerEditOperate(row, res);
          }
        );
      }
    },
    handlerEditOperate (row, res) {
      if (this.widget.relation != null) {
        let tempList = [
          ...this.value
        ];
        if (row == null) {
          // 新增记录
          row = res;
          tempList.push({
            ...row,
            __cascade_add_id__: new Date().getTime()
          });
        } else {
          // 更新记录
          row = res;
          tempList = tempList.map(item => {
            if (row.__cascade_add_id__ != null) {
              return row.__cascade_add_id__ === item.__cascade_add_id__ ? row : item;
            } else {
              return row[this.widget.primaryColumnName] === item[this.widget.primaryColumnName] ? row : item;
            }
          });
        }
        tempList = this.onTableDataListChange(tempList);
        this.$emit('input', tempList);
      }
    },
    onDeleteRow (row) {
      this.$dialog.confirm({
        title: '消息',
        message: '是否删除当前数据？'
      }).then(res => {
        let tempList = [
          ...this.value.filter(data => {
            if (data.__cascade_add_id__ != null) {
              return data.__cascade_add_id__ !== row.__cascade_add_id__;
            } else {
              return data[this.widget.primaryColumnName] !== row[this.widget.primaryColumnName];
            }
          })
        ];
        tempList = this.onTableDataListChange(tempList);
        this.$emit('input', tempList);
      }).catch(e => {});
    }
  },
  computed: {
    cardWidget () {
      return (Array.isArray(this.widget.childWidgetList) && this.widget.childWidgetList.length > 0) ? this.widget.childWidgetList[0] : undefined;
    },
    getComponent () {
      switch (this.widget.props.card) {
        case this.SysCustomWidgetType.ImageCard: return 'online-image-card';
        default:
          return '';
      }
    }
  },
  watch: {
    value: {
      handler () {
        if (this.$refs.list) this.$refs.list.reset();
      },
      immediate: true
    }
  }
}
</script>

<style scoped>
  .add-btn {
    width: 100%;
    margin-bottom: 12px;
    border-style: dashed;
    background: #E5F7E7;
  }
  .list-box .list-item {
    background: #F6F7F9;
    border-radius: 8px;
    margin-bottom: 15px;
  }
</style>
